<template>
  <!-- 编辑论文的对话框 ********************************** -->
  <el-dialog
    title="编辑论文"
    :visible.sync="editDialogVisible"
    width="80%"
    @close="handleEssayEditDialogClose"
    center
    class="projecteditDialog"
  >
    <span>
      <el-row :gutter="20">
        <el-col :span="14"
          ><div class="grid-content bg-purple">
            <el-form
              ref="essayEditFormRef"
              :model="essayEditForm"
              :rules="essayEditFormRules"
              label-width="120px"
              size="mini"
            >
              <el-form-item label="论文标题" prop="name">
                <el-input
                  placeholder="请输入论文名称"
                  v-model="essayEditForm.name"
                ></el-input>
              </el-form-item>
              <!-- 论文编号 -->
              <el-form-item label="论文编号" prop="no">
                <el-input
                  placeholder="请输入论文编号"
                  v-model="essayEditForm.no"
                ></el-input>
              </el-form-item>
              <!-- 关键字 -->
              <el-form-item label="关键字" prop="no">
                <el-input
                  placeholder="请输入论文关键字,逗号分隔"
                  v-model="essayEditForm.keyword"
                  @input="keywordInputChange"
                ></el-input>
              </el-form-item>
              <!-- 作者 -->
              <el-form-item label="作者" prop="author">
                <el-input
                  placeholder="首位是第一作者，次位是其他作者"
                  v-model="essayEditForm.author"
                  @input="authorInputChange"
                ></el-input>
              </el-form-item>
              <!-- 作者单位 -->
              <el-form-item label="作者单位" prop="author_unit">
                <!-- options是数据 -->
                <el-cascader
                  placeholder="请选择作者单位"
                  v-model="author_unitVal"
                  :options="collegeList"
                  :props="{ expandTrigger: 'hover' }"
                  @change="handleAuthor_unitInputChange"
                ></el-cascader>
              </el-form-item>
              <!-- 出版单位 -->
              <el-form-item label="出版单位" prop="publisher">
                <el-input
                  placeholder="请输入出版单位"
                  v-model="essayEditForm.publisher"
                  prop="publisher"
                ></el-input>
              </el-form-item>
              <!-- 发表范围 -->
              <el-form-item label="发表范围" prop="publisher">
                <el-select
                  v-model="essayEditForm.publish_scope"
                  placeholder="请选择发表范围"
                >
                  <el-option
                    v-for="item in publish_scopeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 出版时间 -->
              <el-form-item label="出版时间" prop="publish_time">
                <el-col :span="11">
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="essayEditForm.publish_time"
                    style="width: 100%"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-col>
              </el-form-item>
              <!-- 学科分类 -->
              <el-form-item label="学科分类" prop="subject_classification">
                <!-- options是数据 -->
                <el-cascader
                  placeholder="请选择学科分类"
                  v-model="subject_classificationVal"
                  :options="subject_classificationList"
                  :props="{ expandTrigger: 'hover' }"
                  @change="handleSubject_classificationChange"
                ></el-cascader>
              </el-form-item>
              <!-- 论文分类 -->
              <el-form-item label="论文分类" prop="category">
                <el-input
                  placeholder="请输入论文分类"
                  v-model="essayEditForm.category"
                ></el-input>
              </el-form-item>

              <el-form-item label="摘要" prop="abstract">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="essayEditForm.abstract"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="essayEditForm.remarks"
                >
                </el-input>
              </el-form-item>
            </el-form></div
        ></el-col>
        <!-- 上传模块 -->
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-upload
              ref="essayfileUploadRef"
              class="essayUpload"
              :auto-upload="false"
              drag
              action="http://localhost:3000/essay/edit/upload"
              method="post"
              :on-change="checkType"
              :on-success="uploadSuccess"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传.caj/.pdf文件，且不超过52mb
              </div>
            </el-upload>
          </div></el-col
        >
      </el-row>
    </span>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleProjectEditDialogConfirm"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "myEditEssay",
  props: ["projectList"],
  data() {
    return {
      editDialogVisible: false,
      // 编辑项目数据
      essayEditForm: {},
      // 添加表单的验证规则对象
      essayEditFormRules: {
        name: [{ required: true, message: "请输入论文名", trigger: "blur" }],
        no: [{ required: true, message: "请输入论文编号", trigger: "blur" }],
        keyword: [
          { required: true, message: "请输入论文关键字", trigger: "blur" },
        ],
        author: [{ required: true, message: "请输入作者", trigger: "blur" }],
        author_unit: [
          { required: true, message: "请输入作者单位", trigger: "blur" },
        ],
        publisher: [
          { required: true, message: "请输入出版单位", trigger: "blur" },
        ],
        publish_time: [
          { required: true, message: "请输入出版时间", trigger: "blur" },
        ],
        subject_classification: [
          { required: true, message: "请输入学科分类", trigger: "blur" },
        ],
        category: [
          { required: true, message: "请输入论文分类", trigger: "blur" },
        ],
        abstract: [{ required: true, message: "请输入摘要", trigger: "blur" }],
      },
      // 学科分类
      subject_classificationVal: [],
      // 学院下达单位
      author_unitVal: [],
      isUploadFile: false,
    };
  },
  methods: {
    essayEditDialogVisibleShow(data) {
      this.editDialogVisible = !this.editDialogVisible;

      // 表数据
      this.essayEditForm = data;
      // 同步学科分类
      try {
        let subject_classification = data.subject_classification.split("-");
        // console.log(subject_classification);
        this.subject_classificationList.forEach((item) => {
          if (item.label === subject_classification[0]) {
            item.children.forEach((child) => {
              if (child.label === subject_classification[1]) {
                this.subject_classificationVal = [item.value, child.value];
                throw new Error("forEach end");
              }
            });
          }
        });
      } catch (err) {}

      // 同步作者单位学院下达单位
      try {
        this.collegeList.forEach((item) => {
          if (item.label == data.author_unit) {
            this.author_unitVal[0] = item.value;
            throw new Error("forEach end");
          }
        });
      } catch (err) {}
      // console.log(essayEditForm);
    },

    handleEssayEditDialogClose() {},
    // 学科分类选择事件
    handleSubject_classificationChange(val) {
      this.subject_classificationList.forEach((item) => {
        if (item.value == val[0]) {
          item.children.forEach((child) => {
            if (child.value == val[1]) {
              this.$set(
                this.essayEditForm,
                "subject_classification",
                `${item.label}-${child.label}`
              );
            }
          });
        }
      });
    },
    // 单位选择事件
    handleAuthor_unitInputChange(val) {
      // console.log(val);
      // console.log(this.author_unitVal);
      try {
        this.collegeList.forEach((item) => {
          if (item.value == val[0]) {
            this.$set(this.essayEditForm, "author_unit", item.label);
            throw new Error("EndForEach");
          }
        });
      } catch (err) {}
    },
    // 编辑表单确认上传
    handleProjectEditDialogConfirm() {
      this.$refs.essayEditFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$axios.post("/essay/edit", {
          essayEditForm: this.essayEditForm,
        });

        if (res.status == 100) {
          return this.$refs.essayfileUploadRef.submit();
        } else {
          return this.$message.error(res.message);
        }
      });
    },
    checkType(file, fileList) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      fileList = [];

      if (!(fileType != "caj" || fileType != "pdf")) {
        this.$message.error("文件格式不正确");
        return false;
      }
      if (file.size / 1024 / 1024 > 52) {
        this.$message.error("文件大小不能超过52M");
        return false;
      }
      this.isUploadFile = true;
    },
    uploadSuccess() {
      this.$message.success("添加成功！");
      // 隐藏添加用户的对话框
      this.editDialogVisible = false;
      this.$refs.essayEditFormRef.resetFields();
      this.$bus.$emit("getAchievementList");
    },
    authorInputChange() {
      let cacheData = this.projectAddForm.participant.split("");
      cacheData.forEach((item, index) => {
        if (item === "，") {
          cacheData[index] = ",";
        }
      });
      this.projectAddForm.participant = cacheData.join("");
    },
    // 监听关键字改变事件
    keywordInputChange() {
      // 先变成数组 寻找到中文逗号改变成为英文逗号
      let cacheData = this.essayEditForm.keyword.split("");
      // console.log(cacheData.indexOf("a"));
      cacheData.forEach((item, index) => {
        if (item === "，") {
          // console.log(item);
          cacheData[index] = ",";
        }
      });
      this.essayEditForm.keyword = cacheData.join("");
    },
  },
  mounted() {
    this.$bus.$on(
      "handleIsEssayEditDialogVisibleShow",
      this.essayEditDialogVisibleShow
    );
  },
  beforeDestroy() {
    this.$bus.$off("handleIsEssayEditDialogVisibleShow");
  },
  computed: {
    ...mapState([
      "subject_classificationList",
      "collegeList",
      "publish_scopeOptions",
    ]),
  },
};
</script>

<style lang="less" scoped>
/deep/.el-dialog {
  margin-top: 20px !important;
  margin-bottom: 20px !important;
}
</style>